﻿CREATE PROCEDURE [dbo].[PartyGoodsInsert]
(--создаёт партию и первую проводку по приходу
	@InputLineId int,
	@DocId int,
	@GoodsId int,
	@BarCode char(12),
	@Qntty int,			--фактическое количество
	@RetailPrice decimal(19, 2),  --розничная цена. Д.б. указано если есть фактическое количество
	@ReturnLineId int,
	@Note varchar(250),
	@MD datetime,
	@MW varchar(50),
	@SetNoCount bit
)
AS
DECLARE @strMsg nvarchar(500), @intRet int, @intErrCode int, @intRowCount int
	SET NOCOUNT ON

IF (@GoodsId Is Null) OR (@InputLineId Is Null) OR (@DocId Is Null)
OR (@MD Is Null) OR (@MW Is Null)
BEGIN
	SELECT @intErrCode = 1, @strMsg = 'Неправильные параметры в вызове процедуры ' + Object_Name(@@Procid) + ' !'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF (IsNull(@Qntty,0) <= 0) OR (IsNull(@RetailPrice,0) <= 0)
BEGIN
	SELECT @intErrCode = 203, @strMsg = 'Количество и розничная цена д.б. больше нуля!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @BarCode IS NULL EXEC [dbo].[GetNextBarCode]	@BarCode OUTPUT

INSERT INTO CD.Parties 
(Id, [DocId], [GoodsId], [BarCode], [RetailPrice], InputLineId, [MD], [MW])
VALUES (@InputLineId, @DocId, @GoodsId, @BarCode, @RetailPrice, @InputLineId, @MD, @MW)

SELECT @intErrCode = @@error, @intRowCount = @@rowcount
IF @intErrCode <> 0 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 204, 
	@strMsg = 'Запись в таблицу партий не добавлена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

IF @SetNoCount = 0 SET NOCOUNT OFF

INSERT INTO [CA].[GoodsDocLines]
(Id, DocId, PartyId, [Qntty], [RetailSum], ReturnLineId, [MD], [MW])
VALUES(@InputLineId, @DocId, @InputLineId, @Qntty, @RetailPrice * @Qntty, @ReturnLineId, @MD, @MW);

SELECT @intErrCode = @@error, @intRowCount = @@rowcount
IF @intErrCode <> 0 
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	RETURN @intErrCode
END
IF (@intRowCount <> 1)
BEGIN
	IF @@trancount > 0 ROLLBACK TRAN
	SELECT @intErrCode = 205, 
	@strMsg = 'Запись в таблицу товародвижения не добавлена!'
	RAISERROR (@strMsg, 11, 1)
	RETURN @intErrCode
END

RETURN 0

